package com.guxingke.typecho4j.jfinal.model;

import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

public class Relationships extends Model<Relationships> {
	private static final long serialVersionUID = -1906729065937027274L;
	public static final Relationships dao = new Relationships();

	public void deleteByMid(Long mid) {
		List<Relationships> rs = getByMid(mid);
		if (!rs.isEmpty()) {
			for (Relationships relationships : rs) {
				delete(relationships.getLong("cid"),
						relationships.getLong("mid"));
			}
		}
	}

	public List<Relationships> getByMid(Long mid) {
		return find("select * from typecho_relationships where mid=?",
				mid);
	}

	public boolean delete(Long cid, Long mid) {
		Db.update("delete from typecho_relationships where cid=? and mid=?",
				cid, mid);
		return true;
	}

	public void mergeCategory(Long mid, Long merge) {
		List<Relationships> rs = getByMid(mid);
		if (!rs.isEmpty()) {
			Long cid = null;
			for (Relationships relationship : rs) {
				cid = relationship.getLong("cid");
				delete(relationship.getLong("cid"),
						relationship.getLong("mid"));
				if (getRelationship(cid, mid) == null) {
					Db.save("typecho_relationships",
							new Record().set("cid",
									cid)
									.set("mid",
											merge));
				}
			}
		}
	}

	private Record getRelationship(Long cid, Long mid) {
		return Db.findFirst(
				"select * from typecho_relationships where cid=? and mid=?",
				cid, mid);
	}
}
